package com.sk.weichat.ui.message;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sk.weichat.AppConstant;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.MucRoom;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.broadcast.OtherBroadcast;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.RoomMemberDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.MessageAvatar;
import com.sk.weichat.xmpp.ListenerManager;
import com.sk.weichat.xmpp.listener.ChatMessageListener;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

import static com.sk.weichat.broadcast.OtherBroadcast.RECEIVER_ACTION_FINISH_A;

/**
 * 转发 最近联系人
 */
public class InstantMessageActivity extends BaseActivity implements ChatMessageListener,OnClickListener {

    public  static final int REQUEST_SELECT_CONTACTS = 1010;
    public  static final int REQUEST_SELECT_GROUP = 1011;
    public  static final int RESULT_SELECT_SUCCESS = 1012;
    private TextView mCreateChat, tvSelectFriend, tvSelectGroup;
    private RecyclerView mLvRecentlyMessage;
    private List<Friend> friends;

    private boolean isMoreSelected; // 是否为多选转发
    private boolean isSingleOrMerge; // 逐条还是合并转发
    // 在ChatActivity || MucChatActivity内，通过toUserId与messageId获得该条转发消息 在进行封装
    private String fromUserId;
//    private String NewUserId;//webview 转发临时id
    private String messageId;
    private double message_time;
    private String mLoginUserId;
    private boolean isWeb = false;//判断是否是web跳转进来的
    private String toUserId;

    private InstantMessageConfirm menuWindow;
    private ChatMessage mChatMessage;
    private boolean isContainHistory;//多选转发是否包含聊天记录，包含则不能转发给陌生人

    private MessageRecentlyAdapter mMessageRecentlyAdapter;
    private String toMsgUserId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_messageinstant);
        isMoreSelected = getIntent().getBooleanExtra(Constants.IS_MORE_SELECTED_INSTANT, false);
        isSingleOrMerge = getIntent().getBooleanExtra(Constants.IS_SINGLE_OR_MERGE, false);
        isContainHistory = getIntent().getBooleanExtra(Constants.IS_CONTAIN_HISTORY, false);
        // 在ChatContentView内长按转发才需要以下参数
        fromUserId = getIntent().getStringExtra("fromUserId");
        toUserId = getIntent().getStringExtra("toUserId");
//        NewUserId = getIntent().getStringExtra("NewUserId");
        messageId = getIntent().getStringExtra("messageId");
        message_time = getIntent().getDoubleExtra("message_time",0);
        isWeb = getIntent().getBooleanExtra("isWeb",false);
        mLoginUserId = coreManager.getSelf().getUserId();

        initActionBar();
        loadData();
        initView();
        // 添加新消息来临监听
        ListenerManager.getInstance().addChatMessageListener(this);
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tvTitle = (TextView) findViewById(R.id.tv_title_center);
        tvTitle.setText("转发给");
        TextView tvNearFriend = (TextView) findViewById(R.id.tv_near_friend);
        if(isSingleOrMerge||isContainHistory){
            tvNearFriend.setText(R.string.most_recent_contact_friend);
        }else{
            tvNearFriend.setText(R.string.most_recent_contact);
        }
    }

    private void loadData() {
        if(isSingleOrMerge||isContainHistory){//包含好友、群聊
            friends = FriendDao.getInstance().getNearlyFriends(coreManager.getSelf().getUserId());
            for (int i = 0; i < friends.size(); i++) {
                if (friends.get(i).getUserId().equals(Friend.ID_NEW_FRIEND_MESSAGE)) {
                    friends.remove(i);
                }
            }
        }else{//包含好友、群聊、最近聊天的陌生人
            friends = FriendDao.getInstance().getNearlyFriendMsg(coreManager.getSelf().getUserId());
            for (int i = 0; i < friends.size(); i++) {
                if (friends.get(i).getUserId().equals(Friend.ID_NEW_FRIEND_MESSAGE)) {
                    friends.remove(i);
                }
            }
        }
    }

    private void initView() {
        mCreateChat = findViewById(R.id.tv_create_newmessage);
        mCreateChat.setOnClickListener(this);
        mCreateChat.setVisibility(View.GONE);
        tvSelectFriend = findViewById(R.id.tv_select_friend);
        tvSelectFriend.setVisibility(View.VISIBLE);
        tvSelectFriend.setOnClickListener(this);
        tvSelectGroup = findViewById(R.id.tv_select_group);
        tvSelectGroup.setVisibility(View.VISIBLE);
        tvSelectGroup.setOnClickListener(this);
        mLvRecentlyMessage = findViewById(R.id.lv_recently_message);

        mLvRecentlyMessage.setLayoutManager(new LinearLayoutManager(this));
        mLvRecentlyMessage.setItemViewCacheSize(10);
        mMessageRecentlyAdapter = new MessageRecentlyAdapter(friends);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) mLvRecentlyMessage.getItemAnimator()).setSupportsChangeAnimations(false);
        mMessageRecentlyAdapter.setHasStableIds(true);
        mMessageRecentlyAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Friend friend = friends.get(position);
                toMsgUserId=friend.getUserId();
                showPopuWindow(friend);
            }
        });
        mLvRecentlyMessage.setAdapter(mMessageRecentlyAdapter);
    }

    private void showPopuWindow(Friend friend) {
        menuWindow = new InstantMessageConfirm(InstantMessageActivity.this, new ClickListener(friend), friend);
        menuWindow.show();
//        menuWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.tv_create_newmessage:
                Intent intent = new Intent(this, SelectNewContactsActivity.class);
                intent.putExtra(Constants.IS_MORE_SELECTED_INSTANT, isMoreSelected);
                intent.putExtra(Constants.IS_SINGLE_OR_MERGE, isSingleOrMerge);
                intent.putExtra("fromUserId", fromUserId);
                intent.putExtra("messageId", messageId);
                intent.putExtra("message_time",message_time);
                startActivity(intent);
                finish();
                break;
            case R.id.tv_select_friend:
                Intent intent2 = new Intent(this, SelectNewContactsActivity.class);
                intent2.putExtra(Constants.IS_MORE_SELECTED_INSTANT, isMoreSelected);
                intent2.putExtra(Constants.IS_SINGLE_OR_MERGE, isSingleOrMerge);
//                intent2.putExtra("NewUserId",NewUserId);
                intent2.putExtra("fromUserId", fromUserId);
                intent2.putExtra("messageId", messageId);
                startActivityForResult(intent2,RESULT_SELECT_SUCCESS);

                break;
            case R.id.tv_select_group:
                Intent intent3 = new Intent(InstantMessageActivity.this, SelectNewGroupInstantActivity.class);
                intent3.putExtra(Constants.IS_MORE_SELECTED_INSTANT, isMoreSelected);
                intent3.putExtra(Constants.IS_SINGLE_OR_MERGE, isSingleOrMerge);
//                intent3.putExtra("NewUserId",NewUserId);

                intent3.putExtra("fromUserId", fromUserId);
                intent3.putExtra("messageId", messageId);
                startActivityForResult(intent3,RESULT_SELECT_SUCCESS);
                break;
            default:
                break;
        }
    }

    /**
     * 选择最近联系人转发
     * @param friend
     */
    private void forwardingStep(Friend friend) {
        if (isMoreSelected) {// 多选转发 通知多选页面(即多选消息的单聊 || 群聊页面，在该页面获取选中的消息在发送出去)
            EventBus.getDefault().post(new EventMoreSelected(friend.getUserId(), isSingleOrMerge, friend.getRoomFlag() != 0));
            ToastUtil.showToast(this,"发送成功");
            finish();
        } else {// 普通转发
            if (friend.getRoomFlag() == 0) {// 单聊
                instantChatMessage(friend);
            } else { // 群聊
                instantChatMessage(friend);
            }
        }
    }

    /**
     * 获取自己在该群组的信息(职位、昵称、禁言时间等)以及群属性
     */
    private void isSupportForwarded(final Friend friend) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", friend.getRoomId());

        HttpUtils.get().url(coreManager.getConfig().ROOM_GET_ROOM)
                .params(params)
                .build()
                .execute(new BaseCallback<MucRoom>(MucRoom.class) {

                             @Override
                             public void onResponse(ObjectResult<MucRoom> result) {// 数据结果与room/get接口一样，只是服务端没有返回群成员列表的数据
                                 if (result.getResultCode() == 1 && result.getData() != null) {
                                     final MucRoom mucRoom = result.getData();
                                     if (mucRoom.getMember() == null) {// 被踢出该群组
                                         FriendDao.getInstance().updateFriendGroupStatus(mLoginUserId, mucRoom.getJid(), 1);// 更新本地群组状态
                                         DialogHelper.tip(InstantMessageActivity.this, getString(R.string.tip_forward_kick));
                                     } else {// 正常状态
                                         if (mucRoom.getS() == -1) {// 该群组已被锁定
                                             FriendDao.getInstance().updateFriendGroupStatus(mLoginUserId, mucRoom.getJid(), 3);// 更新本地群组状态
                                             DialogHelper.tip(InstantMessageActivity.this, getString(R.string.tip_group_disable_by_service));
                                             return;
                                         }
                                         int role = mucRoom.getMember().getRole();
                                         // 更新禁言状态
                                         FriendDao.getInstance().updateRoomTalkTime(mLoginUserId, mucRoom.getJid(), mucRoom.getMember().getTalkTime());

                                         // 更新部分群属性
                                         MyApplication.getInstance().saveGroupPartStatus(mucRoom.getJid(), mucRoom.getShowRead(),
                                                 mucRoom.getAllowSendCard(), mucRoom.getAllowConference(),
                                                 mucRoom.getAllowSpeakCourse(), mucRoom.getTalkTime());

                                         // 更新个人职位
                                         RoomMemberDao.getInstance().updateRoomMemberRole(mucRoom.getId(), mLoginUserId, role);

                                         if (role == 1 || role == 2) {// 群组或管理员 直接转发出去
                                             forwardingStep(friend);
                                         } else {
                                             if (mucRoom.getTalkTime() > 0) {// 全体禁言
                                                 DialogHelper.tip(InstantMessageActivity.this, getString(R.string.tip_now_ban_all));
                                             } else if (mucRoom.getMember().getTalkTime() > System.currentTimeMillis() / 1000) {// 禁言
                                                 DialogHelper.tip(InstantMessageActivity.this, getString(R.string.tip_forward_ban));
                                             } else {
                                                 forwardingStep(friend);
                                             }
                                         }
                                     }
                                 } else {// 群组已解散
                                     FriendDao.getInstance().updateFriendGroupStatus(mLoginUserId, friend.getUserId(), 2);// 更新本地群组状态
                                     DialogHelper.tip(InstantMessageActivity.this, getString(R.string.tip_forward_disbanded));
                                 }
                             }

                             @Override
                             public void onError(Call call, Exception e) {
                                 ToastUtil.showNetError(mContext);
                             }
                         }
                );
    }


    /*******************************************
     * 转发&&拦截
     ******************************************/
    private void instantChatMessage(Friend friend) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //NewUserId 判断NewUserId是否为空  如果为空则是通过一般的聊天记录转发，NewUserId不需管  如果不为空则是通过web页转发，需要通过NewUserId查找ChatMessage
                mChatMessage = ChatMessageDao.getInstance().findMsgById(mLoginUserId, fromUserId, messageId);
                mChatMessage.setFromUserId(mLoginUserId);
                mChatMessage.setFromUserName(coreManager.getSelf().getNickName());
                mChatMessage.setToUserId(friend.getUserId());
                mChatMessage.setUpload(true);
                mChatMessage.setMySend(true);
                mChatMessage.setReSendCount(5);
                mChatMessage.setSendRead(false);
                // 因为该消息的原主人可能开启了消息传输加密，我们对于content字段解密后存入了数据库，但是isEncrypt字段并未改变
                // 如果我们将此消息转发给另一人，对方可能会对我方已解密的消息再次进行解密
                mChatMessage.setIsEncrypt(0);
                mChatMessage.setTimeSend(TimeUtils.sk_time_current_time());
                mChatMessage.setPacketId(UUID.randomUUID().toString().replaceAll("-", ""));

                //未回复消息，即打招呼消息
                if(friend.getReplyStatus()==Friend.STATUS_REPLAY_NONE){
                    if ( mChatMessage.getType() == XmppMessage.TYPE_IMAGE
                            || mChatMessage.getType() == XmppMessage.TYPE_VIDEO || mChatMessage.getType() == XmppMessage.TYPE_FILE) {// 语音、图片、视频、文件不能发送

                        mChatMessage.setMessageState(ChatMessageListener.MESSAGE_SEND_OVER);
                    }
                }
                //非好友不能发语音
                if(friend.getStatus()!=Friend.STATUS_FRIEND &&friend.getStatus()!=Friend.STATUS_SYSTEM && mChatMessage.getType() == XmppMessage.TYPE_VOICE){
                    mChatMessage.setMessageState(ChatMessageListener.MESSAGE_SEND_OVER);
                }

                ChatMessageDao.getInstance().saveNewSingleChatMessage(mLoginUserId, friend.getUserId(), mChatMessage);

                if(friend.getStatus()!=Friend.STATUS_FRIEND&&friend.getStatus()!=Friend.STATUS_SYSTEM
                        &&friend.getReplyStatus()==Friend.STATUS_REPLAY_NONE){//未回复消息，即打招呼消息
                    if (mChatMessage.getType() == XmppMessage.TYPE_IMAGE
                            || mChatMessage.getType() == XmppMessage.TYPE_VIDEO || mChatMessage.getType() == XmppMessage.TYPE_FILE) {// 语音、图片、视频、文件不能发送
                        String content="";
                        switch (mChatMessage.getType()){

                            case XmppMessage.TYPE_IMAGE:
                                content="图片发送失败，对方回复后才能使用图片功能";
                                break;
                            case XmppMessage.TYPE_VIDEO:
                                content="视频发送失败，对方回复后才能使用视频功能";
                                break;
                            case XmppMessage.TYPE_FILE:
                                content="文件发送失败，对方回复后才能使用文件功能";
                                break;
                        }

                        //本地添加一个系统提示信息
                        FriendDao.getInstance().addUnReplayInMsgTable(mLoginUserId, mChatMessage.getToUserId(),content);
                        sendMessageSuccess();
                        return;
                    }else{
                        mChatMessage.setMsgType(ChatMessage.TYPE_HELLO);
                    }
                }else  if(friend.getStatus()!=Friend.STATUS_FRIEND && friend.getStatus()!=Friend.STATUS_SYSTEM
                        &&friend.getReplyStatus()==Friend.STATUS_REPLAY_SINGLE){//对方已经单方面发送了打招呼消息
                    mChatMessage.setMsgType(ChatMessage.TYPE_HELLO);
                }

                //非好友不能发送语音消息
                if(friend.getStatus()!=Friend.STATUS_FRIEND && friend.getStatus()!=Friend.STATUS_SYSTEM){
                    if (mChatMessage.getType() == XmppMessage.TYPE_VOICE){
                        String content="互为好友才能发送语音";
                        //本地添加一个系统提示信息
                        FriendDao.getInstance().addUnReplayInMsgTable(mLoginUserId, mChatMessage.getToUserId(),content);
                        sendMessageSuccess();
                        return;
                    }
                }

                if(toUserId.equals(toMsgUserId)){//发给自己
                    Intent intent1 = new Intent(MsgBroadcast.ACTION_MSG_SHARE);
                    sendBroadcast(intent1);
                }
                if(friend.getRoomFlag()==1){//群聊
                    coreManager.sendMucChatMessage(friend.getUserId(), mChatMessage);
                }else{//私聊
                    coreManager.sendChatMessage(friend.getUserId(), mChatMessage);
                }

            }
        }, 1000);
    }

    @Override
    public void onMessageSendStateChange(int messageState, String msgId) {

        if (TextUtils.isEmpty(msgId)) {
            return;
        }
        if (mChatMessage!=null && msgId.equals(mChatMessage.getPacketId())) {
            /**
             * 之前发现对方已经收到消息了，这里还在转圈，退出重进之后又变为送达了，
             * 调试时发现出现该问题是因为消息状态先更新的1，在更新的0，这里处理下
             */
            if (messageState == 1||messageState==ChatMessageListener.MESSAGE_SEND_OVER) {
                sendMessageSuccess();
            }else if(messageState == 2){
                //转发失败
                ToastUtil.showToast(getApplicationContext(),"发送失败");
            }

        }
    }

    public void sendMessageSuccess() {

        ToastUtil.showToast(getApplicationContext(),"发送成功");
        finish();
//        if (!isWeb){
//            //转发成功
////            ToastUtil.showToast(getApplicationContext(),"转发成功");
//            //转发成功 发送广播通知聊天页面关闭（处理通过web转发 重复出现两个聊天页面的情况）
//            Intent intent1 = new Intent(RECEIVER_ACTION_FINISH_A);
//            sendBroadcast(intent1);
//            Friend friend = FriendDao.getInstance().getFriend(mLoginUserId, fromUserId);
//            if(friend.getRoomFlag()==0){//转发好友跳转
//                Intent intent = new Intent(this, ChatActivity.class);
//                intent.putExtra(ChatActivity.FRIEND, friend);
//                intent.putExtra("isserch", true);
//                intent.putExtra("jilu_id",message_time);
//                startActivity(intent);
//            }else{
//                Intent intent = new Intent(InstantMessageActivity.this, MucChatActivity.class);
//                intent.putExtra(AppConstant.EXTRA_USER_ID, friend.getUserId());
//                intent.putExtra(AppConstant.EXTRA_NICK_NAME, friend.getNickName());
//                intent.putExtra("isserch", true);
//                intent.putExtra("jilu_id",message_time);
//                startActivity(intent);
//            }
//        }else {
//            df
//            if(toUserId.equals(toMsgUserId)){//发给自己
//                Intent intent1 = new Intent(MsgBroadcast.ACTION_MSG_SHARE);
//                sendBroadcast(intent1);
//            }
//
//            ToastUtil.showToast(getApplicationContext(),"发送成功");
//        }
//        finish();
    }

    @Override
    public boolean onNewMessage(String fromUserId, ChatMessage message, boolean isGroupMsg) {
        return false;
    }

    /**
     * 事件的监听
     */
    class ClickListener implements OnClickListener {
        private Friend friend;

        public ClickListener(Friend friend) {
            this.friend = friend;
        }

        @Override
        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_send:// 发送
                    if (friend.getRoomFlag() != 0) {// 群组，调接口判断一些群属性状态
                        isSupportForwarded(friend);
                        return;
                    }
                    forwardingStep(friend);
                    break;
                case R.id.btn_cancle:
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case RESULT_SELECT_SUCCESS://选择好友，选择群聊 成功后回调

                toMsgUserId=data.getStringExtra("toUserId");
                if(!TextUtils.isEmpty(toMsgUserId) && toUserId.equals(toMsgUserId)){//发给自己
                    Intent intent1 = new Intent(MsgBroadcast.ACTION_MSG_SHARE);
                    sendBroadcast(intent1);
                }
                ToastUtil.showToast(getApplicationContext(),"发送成功");
                finish();

                break;
        }

    }


    class MessageRecentlyAdapter extends BaseQuickAdapter<Friend, BaseViewHolder> {

        public MessageRecentlyAdapter(@Nullable List<Friend> data) {
            super(R.layout.item_recently_contacts, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, Friend friend) {
            helper.addOnClickListener(R.id.rt_recently_contacts);
            MessageAvatar mIvHead = helper.getView(R.id.iv_recently_contacts_head);
            TextView mTvName = helper.getView(R.id.tv_recently_contacts_name);
            mIvHead.fillData(friend);
            mTvName.setText(TextUtils.isEmpty(friend.getRemarkName()) ? friend.getNickName() : friend.getRemarkName());
        }

//        @Override
//        public View getView(int position, View convertView, ViewGroup parent) {
//            ViewHolder holder;
//            if (convertView == null) {
//                convertView = View.inflate(InstantMessageActivity.this, R.layout.item_recently_contacts, null);
//                holder = new ViewHolder();
//                holder.mIvHead = (MessageAvatar) convertView.findViewById(R.id.iv_recently_contacts_head);
//                holder.mTvName = (TextView) convertView.findViewById(R.id.tv_recently_contacts_name);
//                convertView.setTag(holder);
//            } else {
//                holder = (ViewHolder) convertView.getTag();
//            }
//
//            Friend friend = friends.get(position);
//            holder.mIvHead.fillData(friend);
//            holder.mTvName.setText(TextUtils.isEmpty(friend.getRemarkName()) ? friend.getNickName() : friend.getRemarkName());
//            return convertView;
//        }
    }
//
//    class ViewHolder {
//        MessageAvatar mIvHead;
//        TextView mTvName;
//    }
}
